using DocumentManager.Models;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace DocumentManager.Services;

/// <summary>
/// 导出服务
/// </summary>
public class ExportService
{
    /// <summary>
    /// 导出为Word文档
    /// </summary>
    public async Task<bool> ExportToWordAsync(Models.Document document, string filePath, ExportStyle? style = null)
    {
        try
        {
            style ??= ExportStyle.CreateDefault();
            
            // 创建Word文档
            using var wordDocument = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);
            
            // 添加主要文档部分
            var mainPart = wordDocument.AddMainDocumentPart();
            mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
            var body = mainPart.Document.AppendChild(new Body());

            // 创建样式定义部分
            CreateWordStyles(mainPart, style);

            // 添加文档标题
            AddWordTitle(body, document.Title);

            // 添加文档信息
            AddWordDocumentInfo(body, document);

            // 处理所有节点
            await ProcessNodeForWord(body, document.RootNode, mainPart);

            // 保存文档
            mainPart.Document.Save();
            
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"导出Word文档失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 创建Word文档样式
    /// </summary>
    private void CreateWordStyles(MainDocumentPart mainPart, ExportStyle exportStyle)
    {
        // 添加样式定义部分
        var styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
        var styles = new Styles();

        // 创建文档默认样式
        var docDefaults = new DocDefaults();
        var runPropertiesDefault = new RunPropertiesDefault();
        var runPropertiesBaseStyle = new RunPropertiesBaseStyle();
        runPropertiesBaseStyle.AppendChild(new RunFonts { Ascii = exportStyle.BodyText.FontName, HighAnsi = exportStyle.BodyText.FontName });
        runPropertiesBaseStyle.AppendChild(new FontSize { Val = (exportStyle.BodyText.FontSize * 2).ToString() });
        runPropertiesDefault.AppendChild(runPropertiesBaseStyle);
        docDefaults.AppendChild(runPropertiesDefault);
        styles.AppendChild(docDefaults);

        // 创建文档标题样式
        var titleStyle = CreateWordStyle("DocumentTitle", "文档标题", StyleValues.Paragraph, exportStyle.DocumentTitle);
        styles.AppendChild(titleStyle);

        // 创建各级标题样式
        for (int i = 1; i <= 6; i++)
        {
            var headingStyle = CreateWordHeadingStyle(i, exportStyle.HeadingStyles[i - 1]);
            styles.AppendChild(headingStyle);
        }

        // 创建正文样式
        var normalStyle = CreateWordNormalStyle(exportStyle.BodyText);
        styles.AppendChild(normalStyle);

        // 创建图片说明样式
        var captionStyle = CreateWordCaptionStyle(exportStyle.ImageStyle);
        styles.AppendChild(captionStyle);

        styleDefinitionsPart.Styles = styles;
    }

    /// <summary>
    /// 创建Word样式
    /// </summary>
    private Style CreateWordStyle(string styleId, string styleName, StyleValues type, DocumentTitleStyle titleStyle)
    {
        var style = new Style
        {
            Type = type,
            StyleId = styleId,
            CustomStyle = true
        };

        var styleName1 = new StyleName { Val = styleName };
        var basedOn1 = new BasedOn { Val = "Normal" };
        var nextParagraphStyle1 = new NextParagraphStyle { Val = "Normal" };

        style.AppendChild(styleName1);
        style.AppendChild(basedOn1);
        style.AppendChild(nextParagraphStyle1);

        // 创建样式属性
        var styleRunProperties = new StyleRunProperties();
        styleRunProperties.AppendChild(new RunFonts { Ascii = titleStyle.FontName, HighAnsi = titleStyle.FontName });
        styleRunProperties.AppendChild(new FontSize { Val = (titleStyle.FontSize * 2).ToString() });
        
        if (titleStyle.IsBold)
            styleRunProperties.AppendChild(new Bold());
        if (titleStyle.IsItalic)
            styleRunProperties.AppendChild(new Italic());
        
        if (!string.IsNullOrEmpty(titleStyle.Color) && titleStyle.Color != "#000000")
        {
            var colorHex = titleStyle.Color.TrimStart('#');
            styleRunProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color { Val = colorHex });
        }

        style.AppendChild(styleRunProperties);

        // 创建段落属性
        var styleParagraphProperties = new StyleParagraphProperties();
        var justification = titleStyle.Alignment switch
        {
            Models.TextAlignment.Left => JustificationValues.Left,
            Models.TextAlignment.Center => JustificationValues.Center,
            Models.TextAlignment.Right => JustificationValues.Right,
            Models.TextAlignment.Justify => JustificationValues.Both,
            _ => JustificationValues.Center
        };
        styleParagraphProperties.AppendChild(new Justification { Val = justification });

        if (titleStyle.SpacingAfter > 0)
        {
            styleParagraphProperties.AppendChild(new SpacingBetweenLines 
            { 
                After = (titleStyle.SpacingAfter * 20).ToString()
            });
        }

        style.AppendChild(styleParagraphProperties);

        return style;
    }

    /// <summary>
    /// 创建Word标题样式
    /// </summary>
    private Style CreateWordHeadingStyle(int level, HeadingStyle headingStyle)
    {
        var style = new Style
        {
            Type = StyleValues.Paragraph,
            StyleId = $"Heading{level}",
            CustomStyle = false
        };

        var styleName1 = new StyleName { Val = $"heading {level}" };
        var basedOn1 = new BasedOn { Val = "Normal" };
        var nextParagraphStyle1 = new NextParagraphStyle { Val = "Normal" };

        style.AppendChild(styleName1);
        style.AppendChild(basedOn1);
        style.AppendChild(nextParagraphStyle1);

        // 创建样式运行属性
        var styleRunProperties = new StyleRunProperties();
        styleRunProperties.AppendChild(new RunFonts { Ascii = headingStyle.FontName, HighAnsi = headingStyle.FontName });
        styleRunProperties.AppendChild(new FontSize { Val = (headingStyle.FontSize * 2).ToString() });
        
        if (headingStyle.IsBold)
            styleRunProperties.AppendChild(new Bold());
        if (headingStyle.IsItalic)
            styleRunProperties.AppendChild(new Italic());
        
        if (!string.IsNullOrEmpty(headingStyle.Color) && headingStyle.Color != "#000000")
        {
            var colorHex = headingStyle.Color.TrimStart('#');
            styleRunProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color { Val = colorHex });
        }

        style.AppendChild(styleRunProperties);

        // 创建段落属性
        var styleParagraphProperties = new StyleParagraphProperties();
        var justification = headingStyle.Alignment switch
        {
            Models.TextAlignment.Left => JustificationValues.Left,
            Models.TextAlignment.Center => JustificationValues.Center,
            Models.TextAlignment.Right => JustificationValues.Right,
            Models.TextAlignment.Justify => JustificationValues.Both,
            _ => JustificationValues.Left
        };
        styleParagraphProperties.AppendChild(new Justification { Val = justification });

        // 应用段前段后间距
        if (headingStyle.SpacingBefore > 0 || headingStyle.SpacingAfter > 0)
        {
            var spacing = new SpacingBetweenLines();
            if (headingStyle.SpacingBefore > 0)
                spacing.Before = (headingStyle.SpacingBefore * 20).ToString();
            if (headingStyle.SpacingAfter > 0)
                spacing.After = (headingStyle.SpacingAfter * 20).ToString();
            styleParagraphProperties.AppendChild(spacing);
        }

        // 设置大纲级别
        styleParagraphProperties.AppendChild(new OutlineLevel { Val = level - 1 });

        style.AppendChild(styleParagraphProperties);

        return style;
    }

    /// <summary>
    /// 创建Word正文样式
    /// </summary>
    private Style CreateWordNormalStyle(TextStyle textStyle)
    {
        var style = new Style
        {
            Type = StyleValues.Paragraph,
            StyleId = "Normal",
            Default = true
        };

        var styleName1 = new StyleName { Val = "Normal" };
        style.AppendChild(styleName1);

        // 创建样式运行属性
        var styleRunProperties = new StyleRunProperties();
        styleRunProperties.AppendChild(new RunFonts { Ascii = textStyle.FontName, HighAnsi = textStyle.FontName });
        styleRunProperties.AppendChild(new FontSize { Val = (textStyle.FontSize * 2).ToString() });
        
        if (textStyle.IsBold)
            styleRunProperties.AppendChild(new Bold());
        if (textStyle.IsItalic)
            styleRunProperties.AppendChild(new Italic());
        
        if (!string.IsNullOrEmpty(textStyle.Color) && textStyle.Color != "#000000")
        {
            var colorHex = textStyle.Color.TrimStart('#');
            styleRunProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color { Val = colorHex });
        }

        style.AppendChild(styleRunProperties);

        // 创建段落属性
        var styleParagraphProperties = new StyleParagraphProperties();
        var justification = textStyle.Alignment switch
        {
            Models.TextAlignment.Left => JustificationValues.Left,
            Models.TextAlignment.Center => JustificationValues.Center,
            Models.TextAlignment.Right => JustificationValues.Right,
            Models.TextAlignment.Justify => JustificationValues.Both,
            _ => JustificationValues.Left
        };
        styleParagraphProperties.AppendChild(new Justification { Val = justification });

        // 应用行距和段距
        if (textStyle.LineSpacing != 1.0f || textStyle.ParagraphSpacing > 0)
        {
            var spacing = new SpacingBetweenLines();
            if (textStyle.LineSpacing != 1.0f)
            {
                spacing.Line = ((int)(textStyle.LineSpacing * 240)).ToString();
                spacing.LineRule = LineSpacingRuleValues.Auto;
            }
            if (textStyle.ParagraphSpacing > 0)
            {
                spacing.After = (textStyle.ParagraphSpacing * 20).ToString();
            }
            styleParagraphProperties.AppendChild(spacing);
        }

        style.AppendChild(styleParagraphProperties);

        return style;
    }

    /// <summary>
    /// 创建Word图片说明样式
    /// </summary>
    private Style CreateWordCaptionStyle(ImageStyle imageStyle)
    {
        var style = new Style
        {
            Type = StyleValues.Paragraph,
            StyleId = "Caption",
            CustomStyle = true
        };

        var styleName1 = new StyleName { Val = "Caption" };
        var basedOn1 = new BasedOn { Val = "Normal" };
        var nextParagraphStyle1 = new NextParagraphStyle { Val = "Normal" };

        style.AppendChild(styleName1);
        style.AppendChild(basedOn1);
        style.AppendChild(nextParagraphStyle1);

        // 创建样式运行属性
        var styleRunProperties = new StyleRunProperties();
        styleRunProperties.AppendChild(new RunFonts { Ascii = imageStyle.CaptionFontName, HighAnsi = imageStyle.CaptionFontName });
        styleRunProperties.AppendChild(new FontSize { Val = (imageStyle.CaptionFontSize * 2).ToString() });
        
        if (imageStyle.CaptionItalic)
            styleRunProperties.AppendChild(new Italic());
        
        if (!string.IsNullOrEmpty(imageStyle.CaptionColor) && imageStyle.CaptionColor != "#000000")
        {
            var colorHex = imageStyle.CaptionColor.TrimStart('#');
            styleRunProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color { Val = colorHex });
        }

        style.AppendChild(styleRunProperties);

        // 创建段落属性
        var styleParagraphProperties = new StyleParagraphProperties();
        var justification = imageStyle.CaptionAlignment switch
        {
            ImageAlignment.Left => JustificationValues.Left,
            ImageAlignment.Center => JustificationValues.Center,
            ImageAlignment.Right => JustificationValues.Right,
            _ => JustificationValues.Center
        };
        styleParagraphProperties.AppendChild(new Justification { Val = justification });

        style.AppendChild(styleParagraphProperties);

        return style;
    }

    /// <summary>
    /// 从Word文档导入
    /// </summary>
    public async Task<Models.Document?> ImportFromWordAsync(string filePath)
    {
        try
        {
            using var wordDocument = WordprocessingDocument.Open(filePath, false);
            var mainPart = wordDocument.MainDocumentPart;
            
            if (mainPart?.Document?.Body == null)
                return null;

            var document = new Models.Document
            {
                Title = System.IO.Path.GetFileNameWithoutExtension(filePath),
                Author = Environment.UserName,
                CreatedTime = DateTime.Now,
                Description = "从Word文档导入"
            };

            // 解析Word文档内容
            await ParseWordContent(mainPart.Document.Body, document.RootNode, mainPart);

            return document;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"导入Word文档失败: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 导出为PDF文档
    /// </summary>
    public async Task<bool> ExportToPdfAsync(Models.Document document, string filePath, ExportStyle? style = null)
    {
        try
        {
            style ??= ExportStyle.CreateDefault();
            
            using var fileStream = new FileStream(filePath, FileMode.Create);
            
            // 设置页面大小和方向
            var pageSize = style.PageSettings.PageSize switch
            {
                Models.PageSize.A3 => iTextSharp.text.PageSize.A3,
                Models.PageSize.Letter => new iTextSharp.text.Rectangle(612, 792), // Letter size in points
                Models.PageSize.Legal => new iTextSharp.text.Rectangle(612, 1008), // Legal size in points
                _ => iTextSharp.text.PageSize.A4
            };
            
            if (style.PageSettings.Orientation == PageOrientation.Landscape)
            {
                pageSize = pageSize.Rotate();
            }
            
            // 设置页边距 (转换厘米到点: 1cm = 28.35pt)
            var margins = style.PageSettings.Margins;
            using var pdfDocument = new iTextSharp.text.Document(pageSize, 
                margins.Left * 28.35f, margins.Right * 28.35f, 
                margins.Top * 28.35f, margins.Bottom * 28.35f);
            var writer = PdfWriter.GetInstance(pdfDocument, fileStream);
            
            pdfDocument.Open();

            // 设置字体（支持中文）
            var baseFont = BaseFont.CreateFont("c:/windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            
            // 创建文档标题字体
            var titleFontStyle = iTextSharp.text.Font.NORMAL;
            if (style.DocumentTitle.IsBold) titleFontStyle |= iTextSharp.text.Font.BOLD;
            if (style.DocumentTitle.IsItalic) titleFontStyle |= iTextSharp.text.Font.ITALIC;
            var titleFont = new iTextSharp.text.Font(baseFont, style.DocumentTitle.FontSize, titleFontStyle);
            
            // 创建正文字体
            var bodyFontStyle = iTextSharp.text.Font.NORMAL;
            if (style.BodyText.IsBold) bodyFontStyle |= iTextSharp.text.Font.BOLD;
            if (style.BodyText.IsItalic) bodyFontStyle |= iTextSharp.text.Font.ITALIC;
            var normalFont = new iTextSharp.text.Font(baseFont, style.BodyText.FontSize, bodyFontStyle);

            // 添加文档标题
            var titleParagraph = new iTextSharp.text.Paragraph(document.Title, titleFont);
            titleParagraph.Alignment = style.DocumentTitle.Alignment switch
            {
                Models.TextAlignment.Left => iTextSharp.text.Element.ALIGN_LEFT,
                Models.TextAlignment.Center => iTextSharp.text.Element.ALIGN_CENTER,
                Models.TextAlignment.Right => iTextSharp.text.Element.ALIGN_RIGHT,
                Models.TextAlignment.Justify => iTextSharp.text.Element.ALIGN_JUSTIFIED,
                _ => iTextSharp.text.Element.ALIGN_CENTER
            };
            titleParagraph.SpacingAfter = style.DocumentTitle.SpacingAfter;
            pdfDocument.Add(titleParagraph);
            pdfDocument.Add(new iTextSharp.text.Paragraph(" "));

            // 添加文档信息
            pdfDocument.Add(new iTextSharp.text.Paragraph($"作者: {document.Author}", normalFont));
            pdfDocument.Add(new iTextSharp.text.Paragraph($"创建时间: {document.CreatedTime:yyyy-MM-dd HH:mm:ss}", normalFont));
            if (!string.IsNullOrEmpty(document.Description))
            {
                pdfDocument.Add(new iTextSharp.text.Paragraph($"描述: {document.Description}", normalFont));
            }
            pdfDocument.Add(new iTextSharp.text.Paragraph(" "));

            // 处理所有节点
            await ProcessNodeForPdf(pdfDocument, document.RootNode, normalFont, style);

            pdfDocument.Close();
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"导出PDF文档失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 为Word文档添加标题
    /// </summary>
    private void AddWordTitle(Body body, string title)
    {
        var titleParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        
        // 应用文档标题样式
        var paragraphProperties = new ParagraphProperties();
        paragraphProperties.AppendChild(new ParagraphStyleId { Val = "DocumentTitle" });
        titleParagraph.AppendChild(paragraphProperties);
        
        var titleRun = new Run(new Text(title));
        titleParagraph.AppendChild(titleRun);
        
        body.AppendChild(titleParagraph);
        body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Text(" "))));
    }

    /// <summary>
    /// 为Word文档添加文档信息
    /// </summary>
    private void AddWordDocumentInfo(Body body, Models.Document document)
    {
        body.AppendChild(CreateWordParagraphWithStyle($"作者: {document.Author}", "Normal"));
        body.AppendChild(CreateWordParagraphWithStyle($"创建时间: {document.CreatedTime:yyyy-MM-dd HH:mm:ss}", "Normal"));
        
        if (!string.IsNullOrEmpty(document.Description))
        {
            body.AppendChild(CreateWordParagraphWithStyle($"描述: {document.Description}", "Normal"));
        }
        
        body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Text(" "))));
    }

    /// <summary>
    /// 创建Word段落
    /// </summary>
    private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateWordParagraph(string text, TextStyle? textStyle = null, bool isBold = false, string fontSize = "24")
    {
        var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        var run = new Run();
        var runProperties = new RunProperties();
        
        if (textStyle != null)
        {
            // 应用字体
            runProperties.AppendChild(new RunFonts { Ascii = textStyle.FontName, HighAnsi = textStyle.FontName });
            
            // 应用字号
            runProperties.AppendChild(new FontSize { Val = (textStyle.FontSize * 2).ToString() });
            
            // 应用粗体
            if (textStyle.IsBold)
            {
                runProperties.AppendChild(new Bold());
            }
            
            // 应用斜体
            if (textStyle.IsItalic)
            {
                runProperties.AppendChild(new Italic());
            }
            
            // 应用颜色
            if (!string.IsNullOrEmpty(textStyle.Color) && textStyle.Color != "#000000")
            {
                try
                {
                    var colorHex = textStyle.Color.TrimStart('#');
                    runProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color { Val = colorHex });
                }
                catch { }
            }
            
            // 设置段落属性
            var paragraphProperties = new ParagraphProperties();
            
            // 应用对齐方式
            var justification = textStyle.Alignment switch
            {
                Models.TextAlignment.Left => JustificationValues.Left,
                Models.TextAlignment.Center => JustificationValues.Center,
                Models.TextAlignment.Right => JustificationValues.Right,
                Models.TextAlignment.Justify => JustificationValues.Both,
                _ => JustificationValues.Left
            };
            paragraphProperties.AppendChild(new Justification { Val = justification });
            
            // 应用行距和段距
            if (textStyle.LineSpacing != 1.0f || textStyle.ParagraphSpacing > 0)
            {
                var spacing = new SpacingBetweenLines();
                if (textStyle.LineSpacing != 1.0f)
                {
                    spacing.Line = ((int)(textStyle.LineSpacing * 240)).ToString(); // Word行距单位
                    spacing.LineRule = LineSpacingRuleValues.Auto;
                }
                if (textStyle.ParagraphSpacing > 0)
                {
                    spacing.After = (textStyle.ParagraphSpacing * 20).ToString(); // 段后间距
                }
                paragraphProperties.AppendChild(spacing);
            }
            
            paragraph.AppendChild(paragraphProperties);
        }
        else
        {
            // 使用传统参数
            if (isBold)
            {
                runProperties.AppendChild(new Bold());
            }
            runProperties.AppendChild(new FontSize { Val = fontSize });
        }
        
        run.AppendChild(runProperties);
        run.AppendChild(new Text(text));
        paragraph.AppendChild(run);
        
        return paragraph;
    }

    /// <summary>
    /// 创建带样式的Word段落
    /// </summary>
    private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateWordParagraphWithStyle(string text, string styleId)
    {
        var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        
        // 应用样式
        var paragraphProperties = new ParagraphProperties();
        paragraphProperties.AppendChild(new ParagraphStyleId { Val = styleId });
        paragraph.AppendChild(paragraphProperties);
        
        var run = new Run(new Text(text));
        paragraph.AppendChild(run);
        
        return paragraph;
    }

    /// <summary>
    /// 创建Word标题段落
    /// </summary>
    private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateWordHeadingParagraph(string text, HeadingStyle headingStyle)
    {
        var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        var run = new Run();
        var runProperties = new RunProperties();
        
        // 应用字体
        runProperties.AppendChild(new RunFonts { Ascii = headingStyle.FontName, HighAnsi = headingStyle.FontName });
        
        // 应用字号
        runProperties.AppendChild(new FontSize { Val = (headingStyle.FontSize * 2).ToString() });
        
        // 应用粗体
        if (headingStyle.IsBold)
        {
            runProperties.AppendChild(new Bold());
        }
        
        // 应用斜体
        if (headingStyle.IsItalic)
        {
            runProperties.AppendChild(new Italic());
        }
        
        // 应用颜色
        if (!string.IsNullOrEmpty(headingStyle.Color) && headingStyle.Color != "#000000")
        {
            try
            {
                var colorHex = headingStyle.Color.TrimStart('#');
                runProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color { Val = colorHex });
            }
            catch { }
        }
        
        run.AppendChild(runProperties);
        run.AppendChild(new Text(text));
        paragraph.AppendChild(run);
        
        // 设置段落属性
        var paragraphProperties = new ParagraphProperties();
        
        // 应用对齐方式
        var justification = headingStyle.Alignment switch
        {
            Models.TextAlignment.Left => JustificationValues.Left,
            Models.TextAlignment.Center => JustificationValues.Center,
            Models.TextAlignment.Right => JustificationValues.Right,
            Models.TextAlignment.Justify => JustificationValues.Both,
            _ => JustificationValues.Left
        };
        paragraphProperties.AppendChild(new Justification { Val = justification });
        
        // 应用段前段后间距
        if (headingStyle.SpacingBefore > 0 || headingStyle.SpacingAfter > 0)
        {
            var spacing = new SpacingBetweenLines();
            if (headingStyle.SpacingBefore > 0)
            {
                spacing.Before = (headingStyle.SpacingBefore * 20).ToString();
            }
            if (headingStyle.SpacingAfter > 0)
            {
                spacing.After = (headingStyle.SpacingAfter * 20).ToString();
            }
            paragraphProperties.AppendChild(spacing);
        }
        
        paragraph.AppendChild(paragraphProperties);
        
        return paragraph;
    }

    /// <summary>
    /// 处理节点并添加到Word文档
    /// </summary>
    private async Task ProcessNodeForWord(Body body, DocumentNode node, MainDocumentPart mainPart)
    {
        // 处理标题节点
        if (node.NodeType == DocumentNodeType.Title)
        {
            // 使用对应级别的标题样式
            var styleId = node.Level <= 6 ? $"Heading{node.Level}" : "Heading6";
            body.AppendChild(CreateWordParagraphWithStyle(node.Title, styleId));
        }

        // 处理内容项
        foreach (var content in node.Contents.OrderBy(c => c.Order))
        {
            switch (content)
            {
                case TextContentItem textContent:
                    body.AppendChild(CreateWordParagraphWithStyle(textContent.Text, "Normal"));
                    break;
                    
                case ImageContentItem imageContent:
                    if (imageContent.ImageData != null)
                    {
                        try
                        {
                            await AddSimpleImageToWord(body, imageContent, mainPart);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"添加图片失败: {ex.Message}");
                            body.AppendChild(CreateWordParagraphWithStyle($"[图片: {imageContent.Caption}]", "Normal"));
                        }
                    }
                    else
                    {
                        body.AppendChild(CreateWordParagraphWithStyle($"[图片: {imageContent.Caption}]", "Normal"));
                    }
                    break;
            }
        }

        // 递归处理子节点
        foreach (var child in node.Children)
        {
            await ProcessNodeForWord(body, child, mainPart);
        }
    }

    /// <summary>
    /// 添加简单图片到Word文档（使用更兼容的方式）
    /// </summary>
    private async Task AddSimpleImageToWord(Body body, ImageContentItem imageContent, MainDocumentPart mainPart)
    {
        try
        {
            if (imageContent.ImageData != null && imageContent.ImageData.Length > 0)
            {
                // 创建图片部分
                var imagePart = mainPart.AddImagePart(ImagePartType.Png);
                using var stream = new System.IO.MemoryStream(imageContent.ImageData);
                imagePart.FeedData(stream);

                // 获取关系ID
                var relationshipId = mainPart.GetIdOfPart(imagePart);

                // 创建简化的Drawing元素
                var drawing = CreateSimpleDrawing(relationshipId);
                
                // 创建包含图片的段落
                var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(drawing));
                body.AppendChild(paragraph);

                // 添加图片说明
                if (!string.IsNullOrEmpty(imageContent.Caption))
                {
                    body.AppendChild(CreateWordParagraphWithStyle($"图片说明: {imageContent.Caption}", "Caption"));
                }
            }
            else
            {
                // 使用占位符
                body.AppendChild(CreateWordParagraph($"[图片: {imageContent.Caption}]"));
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"添加图片失败: {ex.Message}");
            body.AppendChild(CreateWordParagraph($"[图片加载失败: {imageContent.Caption}]"));
        }
        
        // 添加空行
        body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Text(" "))));
    }

    /// <summary>
    /// 创建简化的Drawing元素
    /// </summary>
    private Drawing CreateSimpleDrawing(string relationshipId)
    {
        var drawing = new Drawing();
        
        var inline = new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline();
        
        // 设置默认图片大小 (EMU单位: 914400 EMU = 1英寸)
        var width = 4500000L;  // 约5英寸
        var height = 3400000L; // 约3.75英寸
        
        inline.Extent = new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = width, Cy = height };
        inline.EffectExtent = new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent() 
        { 
            LeftEdge = 0L, 
            TopEdge = 0L, 
            RightEdge = 0L, 
            BottomEdge = 0L 
        };
        
        inline.DocProperties = new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties() 
        { 
            Id = 1U, 
            Name = "Picture 1" 
        };
        
        var graphic = new DocumentFormat.OpenXml.Drawing.Graphic();
        var graphicData = new DocumentFormat.OpenXml.Drawing.GraphicData() 
        { 
            Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" 
        };
        
        var picture = new DocumentFormat.OpenXml.Drawing.Pictures.Picture();
        picture.NonVisualPictureProperties = new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureProperties();
        picture.NonVisualPictureProperties.NonVisualDrawingProperties = 
            new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualDrawingProperties() 
            { 
                Id = 0U, 
                Name = "Picture" 
            };
        picture.NonVisualPictureProperties.NonVisualPictureDrawingProperties = 
            new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureDrawingProperties();
        
        var blipFill = new DocumentFormat.OpenXml.Drawing.Pictures.BlipFill();
        var blip = new DocumentFormat.OpenXml.Drawing.Blip() { Embed = relationshipId };
        var stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
        stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
        
        blipFill.AppendChild(blip);
        blipFill.AppendChild(stretch);
        picture.BlipFill = blipFill;
        
        var shapeProperties = new DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties();
        var transform2D = new DocumentFormat.OpenXml.Drawing.Transform2D();
        var offset = new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L };
        var extents = new DocumentFormat.OpenXml.Drawing.Extents() { Cx = width, Cy = height };
        
        transform2D.Offset = offset;
        transform2D.Extents = extents;
        shapeProperties.Transform2D = transform2D;
        
        var presetGeometry = new DocumentFormat.OpenXml.Drawing.PresetGeometry() 
        { 
            Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle 
        };
        presetGeometry.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
        shapeProperties.AppendChild(presetGeometry);
        
        picture.ShapeProperties = shapeProperties;
        
        graphicData.AppendChild(picture);
        graphic.GraphicData = graphicData;
        inline.Graphic = graphic;
        drawing.Inline = inline;
        
        return drawing;
    }

    /// <summary>
    /// 处理节点并添加到PDF文档
    /// </summary>
    private async Task ProcessNodeForPdf(iTextSharp.text.Document pdfDocument, DocumentNode node, 
        iTextSharp.text.Font normalFont, ExportStyle style)
    {
        // 处理标题节点
        if (node.NodeType == DocumentNodeType.Title)
        {
            // 获取对应级别的标题样式
            var headingStyle = node.Level <= 6 ? style.HeadingStyles[node.Level - 1] : style.HeadingStyles[5];
            
            // 创建标题字体
            var baseFont = BaseFont.CreateFont("c:/windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var fontStyle = iTextSharp.text.Font.NORMAL;
            if (headingStyle.IsBold) fontStyle |= iTextSharp.text.Font.BOLD;
            if (headingStyle.IsItalic) fontStyle |= iTextSharp.text.Font.ITALIC;
            var headingFont = new iTextSharp.text.Font(baseFont, headingStyle.FontSize, fontStyle);
            
            var headingParagraph = new iTextSharp.text.Paragraph(node.Title, headingFont);
            
            // 应用对齐方式
            headingParagraph.Alignment = headingStyle.Alignment switch
            {
                Models.TextAlignment.Left => iTextSharp.text.Element.ALIGN_LEFT,
                Models.TextAlignment.Center => iTextSharp.text.Element.ALIGN_CENTER,
                Models.TextAlignment.Right => iTextSharp.text.Element.ALIGN_RIGHT,
                Models.TextAlignment.Justify => iTextSharp.text.Element.ALIGN_JUSTIFIED,
                _ => iTextSharp.text.Element.ALIGN_LEFT
            };
            
            // 应用间距
            headingParagraph.SpacingBefore = headingStyle.SpacingBefore;
            headingParagraph.SpacingAfter = headingStyle.SpacingAfter;
            
            pdfDocument.Add(headingParagraph);
        }

        // 处理内容项
        foreach (var content in node.Contents.OrderBy(c => c.Order))
        {
            switch (content)
            {
                case TextContentItem textContent:
                    var textParagraph = new iTextSharp.text.Paragraph(textContent.Text, normalFont);
                    
                    // 应用正文样式的对齐方式
                    textParagraph.Alignment = style.BodyText.Alignment switch
                    {
                        Models.TextAlignment.Left => iTextSharp.text.Element.ALIGN_LEFT,
                        Models.TextAlignment.Center => iTextSharp.text.Element.ALIGN_CENTER,
                        Models.TextAlignment.Right => iTextSharp.text.Element.ALIGN_RIGHT,
                        Models.TextAlignment.Justify => iTextSharp.text.Element.ALIGN_JUSTIFIED,
                        _ => iTextSharp.text.Element.ALIGN_LEFT
                    };
                    
                    // 应用行距和段距
                    textParagraph.Leading = style.BodyText.FontSize * style.BodyText.LineSpacing;
                    textParagraph.SpacingAfter = style.BodyText.ParagraphSpacing;
                    
                    pdfDocument.Add(textParagraph);
                    break;
                    
                case ImageContentItem imageContent:
                    await AddImageToPdf(pdfDocument, imageContent, style.ImageStyle);
                    break;
            }
        }

        // 递归处理子节点
        foreach (var child in node.Children)
        {
            await ProcessNodeForPdf(pdfDocument, child, normalFont, style);
        }
    }

    /// <summary>
    /// 添加图片到PDF文档
    /// </summary>
    private async Task AddImageToPdf(iTextSharp.text.Document pdfDocument, ImageContentItem imageContent, ImageStyle imageStyle)
    {
        try
        {
            if (imageContent.ImageData != null)
            {
                var image = iTextSharp.text.Image.GetInstance(imageContent.ImageData);
                
                // 使用样式中的最大尺寸设置
                var maxWidth = Math.Min(imageStyle.MaxWidth, pdfDocument.PageSize.Width - 100);
                var maxHeight = Math.Min(imageStyle.MaxHeight, pdfDocument.PageSize.Height - 200);
                
                if (image.Width > maxWidth || image.Height > maxHeight)
                {
                    image.ScaleToFit(maxWidth, maxHeight);
                }
                
                // 应用图片对齐方式
                image.Alignment = imageStyle.Alignment switch
                {
                    ImageAlignment.Left => iTextSharp.text.Element.ALIGN_LEFT,
                    ImageAlignment.Center => iTextSharp.text.Element.ALIGN_CENTER,
                    ImageAlignment.Right => iTextSharp.text.Element.ALIGN_RIGHT,
                    _ => iTextSharp.text.Element.ALIGN_CENTER
                };
                
                pdfDocument.Add(image);

                // 添加图片说明
                if (imageStyle.ShowCaption && !string.IsNullOrEmpty(imageContent.Caption))
                {
                    var baseFont = BaseFont.CreateFont("c:/windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    
                    // 创建说明字体样式
                    var captionFontStyle = iTextSharp.text.Font.NORMAL;
                    if (imageStyle.CaptionItalic) captionFontStyle |= iTextSharp.text.Font.ITALIC;
                    var captionFont = new iTextSharp.text.Font(baseFont, imageStyle.CaptionFontSize, captionFontStyle);
                    
                    var captionParagraph = new iTextSharp.text.Paragraph($"图片说明: {imageContent.Caption}", captionFont);
                    
                    // 应用说明对齐方式
                    captionParagraph.Alignment = imageStyle.CaptionAlignment switch
                    {
                        ImageAlignment.Left => iTextSharp.text.Element.ALIGN_LEFT,
                        ImageAlignment.Center => iTextSharp.text.Element.ALIGN_CENTER,
                        ImageAlignment.Right => iTextSharp.text.Element.ALIGN_RIGHT,
                        _ => iTextSharp.text.Element.ALIGN_CENTER
                    };
                    
                    pdfDocument.Add(captionParagraph);
                }
                
                pdfDocument.Add(new iTextSharp.text.Paragraph(" "));
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"添加图片到PDF失败: {ex.Message}");
            var baseFont = BaseFont.CreateFont("c:/windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var errorFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL);
            pdfDocument.Add(new iTextSharp.text.Paragraph($"[图片加载失败: {imageContent.Caption}]", errorFont));
        }
    }

    /// <summary>
    /// 获取Word标题字体大小
    /// </summary>
    private string GetWordHeadingSize(int level)
    {
        return level switch
        {
            1 => "32",
            2 => "28",
            3 => "26",
            4 => "24",
            5 => "22",
            6 => "20",
            _ => "24"
        };
    }

    /// <summary>
    /// 获取PDF标题字体大小
    /// </summary>
    private float GetPdfHeadingSize(int level)
    {
        return level switch
        {
            1 => 16f,
            2 => 14f,
            3 => 13f,
            4 => 12f,
            5 => 11f,
            6 => 10f,
            _ => 12f
        };
    }

    /// <summary>
    /// 解析Word文档内容
    /// </summary>
    private async Task ParseWordContent(Body body, DocumentNode rootNode, MainDocumentPart mainPart)
    {
        var currentNode = rootNode;
        var nodeStack = new Stack<DocumentNode>();
        nodeStack.Push(rootNode);

        // 先扫描整个文档中的所有图片，以便调试
        await ScanAllImagesInDocument(mainPart, rootNode);
        System.Diagnostics.Debug.WriteLine("=== 开始解析Word文档段落 ===");

        foreach (var element in body.Elements())
        {
            switch (element)
            {
                case DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph:
                    await ProcessWordParagraph(paragraph, currentNode, nodeStack, mainPart);
                    currentNode = nodeStack.Peek();
                    break;

                case DocumentFormat.OpenXml.Wordprocessing.Table table:
                    // 处理表格中的图片
                    await ProcessTableImages(table, currentNode, mainPart);
                    // 转换表格为文本
                    ProcessWordTable(table, currentNode);
                    break;
            }
        }
    }

    /// <summary>
    /// 扫描文档中的所有图片（用于调试）
    /// </summary>
    private async Task ScanAllImagesInDocument(MainDocumentPart mainPart, DocumentNode rootNode)
    {
        try
        {
            System.Diagnostics.Debug.WriteLine("=== 开始扫描文档中的所有图片 ===");
            
            // 获取所有图片部分
            var imageParts = mainPart.ImageParts.ToList();
            System.Diagnostics.Debug.WriteLine($"文档中共有 {imageParts.Count} 个图片部分");

            foreach (var imagePart in imageParts)
            {
                try
                {
                    var relationshipId = mainPart.GetIdOfPart(imagePart);
                    var contentType = imagePart.ContentType;
                    
                    using var stream = imagePart.GetStream();
                    var size = stream.Length;
                    
                    System.Diagnostics.Debug.WriteLine($"图片: ID={relationshipId}, 类型={contentType}, 大小={size} 字节");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"扫描图片部分失败: {ex.Message}");
                }
            }

            // 查找所有Drawing元素
            var allDrawings = mainPart.Document.Descendants<Drawing>().ToList();
            System.Diagnostics.Debug.WriteLine($"文档中共有 {allDrawings.Count} 个Drawing元素");

            // 查找所有Blip元素
            var allBlips = mainPart.Document.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().ToList();
            System.Diagnostics.Debug.WriteLine($"文档中共有 {allBlips.Count} 个Blip元素");

            // 查找所有VML ImageData元素 (如果存在)
            try
            {
                var allVmlImages = mainPart.Document.Descendants().Where(e => e.LocalName == "imagedata").ToList();
                System.Diagnostics.Debug.WriteLine($"文档中共有 {allVmlImages.Count} 个VML ImageData元素");
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine("VML ImageData元素检查跳过");
            }

            System.Diagnostics.Debug.WriteLine("=== 扫描完成 ===");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"扫描文档图片失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 处理表格中的图片
    /// </summary>
    private async Task ProcessTableImages(DocumentFormat.OpenXml.Wordprocessing.Table table, DocumentNode currentNode, MainDocumentPart mainPart)
    {
        try
        {
            var tableBlips = table.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().ToList();
            if (tableBlips.Any())
            {
                var processedEmbeds = new HashSet<string>();
                int imageCount = await ProcessBlipImages(tableBlips, currentNode, mainPart, processedEmbeds);
                System.Diagnostics.Debug.WriteLine($"表格中处理了 {imageCount} 个图片");
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"处理表格图片失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 处理Word段落
    /// </summary>
    private async Task ProcessWordParagraph(DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph, 
        DocumentNode currentNode, Stack<DocumentNode> nodeStack, MainDocumentPart mainPart)
    {
        var paragraphText = GetParagraphText(paragraph);
        
        // 检查是否是标题
        var headingLevel = GetHeadingLevel(paragraph);
        
        if (headingLevel > 0 && !string.IsNullOrWhiteSpace(paragraphText))
        {
            // 创建标题节点
            var titleNode = new DocumentNode
            {
                NodeType = DocumentNodeType.Title,
                Title = paragraphText.Trim(),
                Level = headingLevel
            };

            // 调整节点层级
            AdjustNodeHierarchy(nodeStack, headingLevel);
            var parentNode = nodeStack.Peek();
            parentNode.Children.Add(titleNode);
            nodeStack.Push(titleNode);
        }
        else
        {
            // 处理图片（无论是否有文本）
            await ProcessAllImageTypes(paragraph, currentNode, mainPart);

            // 添加文本内容（如果有）
            if (!string.IsNullOrWhiteSpace(paragraphText))
            {
                var textContent = new TextContentItem
                {
                    Text = paragraphText.Trim(),
                    Order = currentNode.Contents.Count
                };
                currentNode.Contents.Add(textContent);
            }
        }
    }

    /// <summary>
    /// 获取段落文本
    /// </summary>
    private string GetParagraphText(DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph)
    {
        var texts = paragraph.Descendants<Text>().Select(t => t.Text);
        return string.Join("", texts);
    }

    /// <summary>
    /// 获取标题级别
    /// </summary>
    private int GetHeadingLevel(DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph)
    {
        var paragraphProperties = paragraph.ParagraphProperties;
        if (paragraphProperties?.ParagraphStyleId?.Val?.Value != null)
        {
            var styleId = paragraphProperties.ParagraphStyleId.Val.Value;
            
            // 检查常见的标题样式
            if (styleId.StartsWith("Heading") || styleId.StartsWith("heading"))
            {
                var levelStr = styleId.Substring(styleId.Length - 1);
                if (int.TryParse(levelStr, out int level) && level >= 1 && level <= 6)
                {
                    return level;
                }
            }
        }

        // 检查字体大小来推断标题级别
        var runProperties = paragraph.Descendants<RunProperties>().FirstOrDefault();
        if (runProperties?.FontSize?.Val?.Value != null)
        {
            var fontSize = int.Parse(runProperties.FontSize.Val.Value) / 2; // Word中字体大小是磅数的两倍
            
            return fontSize switch
            {
                >= 18 => 1,
                >= 16 => 2,
                >= 14 => 3,
                >= 13 => 4,
                >= 12 => 5,
                >= 11 => 6,
                _ => 0
            };
        }

        // 检查是否加粗
        var isBold = paragraph.Descendants<Bold>().Any();
        if (isBold && !string.IsNullOrWhiteSpace(GetParagraphText(paragraph)))
        {
            var text = GetParagraphText(paragraph).Trim();
            if (text.Length < 100) // 短文本且加粗，可能是标题
            {
                return 3; // 默认为3级标题
            }
        }

        return 0; // 不是标题
    }

    /// <summary>
    /// 调整节点层级结构
    /// </summary>
    private void AdjustNodeHierarchy(Stack<DocumentNode> nodeStack, int newLevel)
    {
        // 弹出比当前级别深的节点
        while (nodeStack.Count > 1)
        {
            var topNode = nodeStack.Peek();
            if (topNode.Level >= newLevel)
            {
                nodeStack.Pop();
            }
            else
            {
                break;
            }
        }
    }

    /// <summary>
    /// 处理所有类型的图片
    /// </summary>
    private async Task ProcessAllImageTypes(DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph, 
        DocumentNode currentNode, MainDocumentPart mainPart)
    {
        try
        {
            // 使用HashSet防止重复处理同一个图片
            var processedEmbeds = new HashSet<string>();
            int actualImageCount = 0;
            
            // 方法1: 处理Inline图片
            var inlineImages = paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline>().ToList();
            if (inlineImages.Any())
            {
                System.Diagnostics.Debug.WriteLine($"发现 {inlineImages.Count} 个Inline图片");
                actualImageCount += await ProcessInlineImages(inlineImages, currentNode, mainPart, processedEmbeds);
            }

            // 方法2: 处理Anchor图片 (浮动图片)
            var anchorImages = paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Wordprocessing.Anchor>().ToList();
            if (anchorImages.Any())
            {
                System.Diagnostics.Debug.WriteLine($"发现 {anchorImages.Count} 个Anchor图片");
                actualImageCount += await ProcessAnchorImages(anchorImages, currentNode, mainPart, processedEmbeds);
            }

            // 方法3: 处理遗漏的Blip元素（不在Inline/Anchor中的）
            var allBlips = paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().ToList();
            var orphanBlips = allBlips.Where(b => b.Embed?.Value != null && !processedEmbeds.Contains(b.Embed.Value)).ToList();
            if (orphanBlips.Any())
            {
                System.Diagnostics.Debug.WriteLine($"发现 {orphanBlips.Count} 个孤立的Blip元素");
                actualImageCount += await ProcessBlipImages(orphanBlips, currentNode, mainPart, processedEmbeds);
            }

            // 方法4: 查找VML图片 (兼容模式图片)
            try
            {
                var vmlImages = paragraph.Descendants().Where(e => e.LocalName == "imagedata").ToList();
                if (vmlImages.Any())
                {
                    System.Diagnostics.Debug.WriteLine($"发现 {vmlImages.Count} 个VML图片");
                    actualImageCount += await ProcessVmlImagesGeneric(vmlImages, currentNode, mainPart, processedEmbeds);
                }
            }
            catch (Exception vmlEx)
            {
                System.Diagnostics.Debug.WriteLine($"VML图片处理异常: {vmlEx.Message}");
            }

            if (actualImageCount > 0)
            {
                System.Diagnostics.Debug.WriteLine($"段落实际处理了 {actualImageCount} 个不重复的图片");
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"处理段落图片失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 处理Inline图片
    /// </summary>
    private async Task<int> ProcessInlineImages(IEnumerable<DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline> images, 
        DocumentNode currentNode, MainDocumentPart mainPart, HashSet<string> processedEmbeds)
    {
        int processedCount = 0;
        foreach (var inline in images)
        {
            try
            {
                var blip = inline.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                if (blip?.Embed?.Value != null && !processedEmbeds.Contains(blip.Embed.Value))
                {
                    await ExtractImageFromPart(blip.Embed.Value, currentNode, mainPart, "Inline图片");
                    processedEmbeds.Add(blip.Embed.Value);
                    processedCount++;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理Inline图片失败: {ex.Message}");
            }
        }
        return processedCount;
    }

    /// <summary>
    /// 处理Anchor图片 (浮动图片)
    /// </summary>
    private async Task<int> ProcessAnchorImages(IEnumerable<DocumentFormat.OpenXml.Drawing.Wordprocessing.Anchor> images, 
        DocumentNode currentNode, MainDocumentPart mainPart, HashSet<string> processedEmbeds)
    {
        int processedCount = 0;
        foreach (var anchor in images)
        {
            try
            {
                var blip = anchor.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                if (blip?.Embed?.Value != null && !processedEmbeds.Contains(blip.Embed.Value))
                {
                    await ExtractImageFromPart(blip.Embed.Value, currentNode, mainPart, "浮动图片");
                    processedEmbeds.Add(blip.Embed.Value);
                    processedCount++;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理Anchor图片失败: {ex.Message}");
            }
        }
        return processedCount;
    }

    /// <summary>
    /// 处理Blip图片 (直接查找)
    /// </summary>
    private async Task<int> ProcessBlipImages(IEnumerable<DocumentFormat.OpenXml.Drawing.Blip> blips, 
        DocumentNode currentNode, MainDocumentPart mainPart, HashSet<string> processedEmbeds)
    {
        int processedCount = 0;

        foreach (var blip in blips)
        {
            try
            {
                if (blip?.Embed?.Value != null && !processedEmbeds.Contains(blip.Embed.Value))
                {
                    await ExtractImageFromPart(blip.Embed.Value, currentNode, mainPart, "Blip图片");
                    processedEmbeds.Add(blip.Embed.Value);
                    processedCount++;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理Blip图片失败: {ex.Message}");
            }
        }
        return processedCount;
    }

    /// <summary>
    /// 处理VML图片 (兼容模式) - 通用版本
    /// </summary>
    private async Task<int> ProcessVmlImagesGeneric(IEnumerable<OpenXmlElement> images, 
        DocumentNode currentNode, MainDocumentPart mainPart, HashSet<string> processedEmbeds)
    {
        int processedCount = 0;
        foreach (var imageData in images)
        {
            try
            {
                // 尝试获取关系ID属性
                var relIdAttr = imageData.GetAttributes().FirstOrDefault(a => a.LocalName == "id");
                if (relIdAttr != null && !string.IsNullOrEmpty(relIdAttr.Value) && !processedEmbeds.Contains(relIdAttr.Value))
                {
                    await ExtractImageFromPart(relIdAttr.Value, currentNode, mainPart, "VML图片");
                    processedEmbeds.Add(relIdAttr.Value);
                    processedCount++;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理VML图片失败: {ex.Message}");
            }
        }
        return processedCount;
    }

    /// <summary>
    /// 从图片部分提取图片数据
    /// </summary>
    private async Task ExtractImageFromPart(string relationshipId, DocumentNode currentNode, 
        MainDocumentPart mainPart, string imageType)
    {
        try
        {
            var part = mainPart.GetPartById(relationshipId);
            
            if (part is ImagePart imagePart)
            {
                using var stream = imagePart.GetStream();
                using var memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                
                var imageData = memoryStream.ToArray();
                if (imageData.Length > 0)
                {
                    var imageContent = new ImageContentItem
                    {
                        ImageData = imageData,
                        Caption = $"导入的{imageType}",
                        Order = currentNode.Contents.Count
                    };
                    
                    // 立即加载图片源，使其在UI中显示
                    imageContent.LoadImageFromData();
                    
                    currentNode.Contents.Add(imageContent);
                    
                    System.Diagnostics.Debug.WriteLine($"成功导入{imageType}: {imageData.Length} 字节");
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"关系ID {relationshipId} 对应的不是图片部分: {part?.GetType().Name}");
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"提取图片失败 (关系ID: {relationshipId}): {ex.Message}");
        }
    }

    /// <summary>
    /// 处理Word表格
    /// </summary>
    private void ProcessWordTable(DocumentFormat.OpenXml.Wordprocessing.Table table, DocumentNode currentNode)
    {
        try
        {
            var tableText = new System.Text.StringBuilder();
            tableText.AppendLine("--- 表格内容 ---");

            foreach (var row in table.Elements<TableRow>())
            {
                var rowText = new List<string>();
                foreach (var cell in row.Elements<TableCell>())
                {
                    var cellText = string.Join(" ", cell.Descendants<Text>().Select(t => t.Text));
                    rowText.Add(cellText.Trim());
                }
                tableText.AppendLine(string.Join(" | ", rowText));
            }

            tableText.AppendLine("--- 表格结束 ---");

            var textContent = new TextContentItem
            {
                Text = tableText.ToString(),
                Order = currentNode.Contents.Count
            };
            currentNode.Contents.Add(textContent);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"处理表格失败: {ex.Message}");
        }
    }
} 